package com.cxs.xiaomi.web.lisitener;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import cxs.utils.utils.JdbcUtil;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/*
 * @Author:cxs
 * @Date:2021/9/14  15:57
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * 处理阿里连接池资源未释放的监听器
 * */
@WebListener
public class AppServletContextClearLisitener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("服务器已启动.....");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 获取打开的驱动并关闭
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()){
            try {
                DriverManager.deregisterDriver(drivers.nextElement());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 释放线程资源
        AbandonedConnectionCleanupThread.checkedShutdown();

        // 关闭数据源
        DruidDataSource dataSource = (DruidDataSource) JdbcUtil.getDataSource();
        dataSource.close();
    }
}
